package com.ihomey.linkuphome.ui;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.github.ikidou.fragmentBackHandler.FragmentBackHandler;
import com.ihomey.cc.library.util.DensityUtil;
import com.ihomey.linkuphome.DeviceController;
import com.ihomey.linkuphome.DividerDecoration;
import com.ihomey.linkuphome.R;
import com.ihomey.linkuphome.SpacesItemDecoration;
import com.ihomey.linkuphome.adapter.AddedCategoryAdapter;
import com.ihomey.linkuphome.adapter.LanguageListAdapter;
import com.ihomey.linkuphome.adapter.UnAddedCategoryAdapter;
import com.ihomey.linkuphome.base.BaseFragment;
import com.ihomey.linkuphome.database.DataBaseDataSource;
import com.ihomey.linkuphome.entities.Category;
import com.ihomey.linkuphome.listeners.OnItemClickListener;
import com.ihomey.linkuphome.util.BindView;
import com.ihomey.linkuphome.widget.swipemenulistview.SwipeMenu;
import com.ihomey.linkuphome.widget.swipemenulistview.SwipeMenuCreator;
import com.ihomey.linkuphome.widget.swipemenulistview.SwipeMenuItem;
import com.ihomey.linkuphome.widget.swipemenulistview.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/9.
 */

public class HomeFragment extends BaseFragment implements FragmentBackHandler, AdapterView.OnItemClickListener, SwipeMenuListView.OnMenuItemClickListener, View.OnClickListener {

    @BindView(id = R.id.smlv_home_category)
    private SwipeMenuListView swipeMenuListView;
    @BindView(id = R.id.rcv_category)
    public RecyclerView rcv_category;
    @BindView(id = R.id.rcv_language)
    public RecyclerView rcv_language;
    @BindView(id = R.id.blackView)
    public View blackView;
    @BindView(id = R.id.inc_emptyView)
    public View inc_emptyView;


    private MainActivity mainActivity;

    private AddedCategoryAdapter addedCategoriesAdapter;
    private UnAddedCategoryAdapter unAddedCategoriesAdapter;
    private LanguageListAdapter languageListAdapter;
    public BottomSheetBehavior behavior1;
    public BottomSheetBehavior behavior2;

    private List<Category> addedCategories = new ArrayList<>();
    private List<Category> unAddedCategories = new ArrayList<>();
    private String[] languageArray;

    private DataBaseDataSource dataBaseDataSource;
    private DeviceController mController;


    public DataBaseDataSource getDataBaseDataSource() {
        if (dataBaseDataSource == null) {
            dataBaseDataSource = new DataBaseDataSource(getActivity());
        }
        return dataBaseDataSource;
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.fragment_home, null);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mainActivity = (MainActivity) activity;
            mController = (DeviceController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DeviceController callback interface.");
        }
    }


    @Override
    public void initData() {
        super.initData();
        addedCategories = getDataBaseDataSource().getCategories(true);
        unAddedCategories = getDataBaseDataSource().getCategories(false);
        addedCategoriesAdapter = new AddedCategoryAdapter(getActivity(), addedCategories);
        unAddedCategoriesAdapter = new UnAddedCategoryAdapter(getActivity(), unAddedCategories);
        languageArray = getResources().getStringArray(R.array.language_array);
        languageListAdapter = new LanguageListAdapter(languageArray);
    }

    @Override
    public void initWidget(View view) {
        super.initWidget(view);
        initHeader();
        initCategoryRcv();
        initLanguageRcv();
        initSwipeMenuListView();
        initBehavior();
    }

    private void initBehavior() {
        blackView.setVisibility(View.GONE);
        blackView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                behavior1.setState(BottomSheetBehavior.STATE_COLLAPSED);
                behavior2.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
        behavior1 = BottomSheetBehavior.from(rcv_category);
        behavior2 = BottomSheetBehavior.from(rcv_language);
        behavior1.setBottomSheetCallback(new BottomSheetCallback());
        behavior2.setBottomSheetCallback(new BottomSheetCallback());
    }

    private void initHeader() {
        mainActivity.showBackBtn(false);
        mainActivity.setTitle(R.string.title_activity_home);
        if (mainActivity.getLanguage().equals("en")) {
            mainActivity.setRightText(languageArray[0]);
        } else if (mainActivity.getLanguage().equals("zh")) {
            mainActivity.setRightText(languageArray[1]);
        } else if (mainActivity.getLanguage().equals("fr")) {
            mainActivity.setRightText(languageArray[2]);
        } else if (mainActivity.getLanguage().equals("de")) {
            mainActivity.setRightText(languageArray[3]);
        } else if (mainActivity.getLanguage().equals("es")) {
            mainActivity.setRightText(languageArray[4]);
        }
        mainActivity.getRightTv().setOnClickListener(this);
    }

    private void initSwipeMenuListView() {
        View emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.category_empty_view, null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.CENTER;
        ((ViewGroup) swipeMenuListView.getParent()).addView(emptyView, layoutParams);
        swipeMenuListView.setEmptyView(emptyView);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                behavior1.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });
        inc_emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                behavior1.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                if (menu.getViewType() == 0) {
                    SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                    deleteItem.setBackground(R.drawable.item_menu_delete_selector);
                    deleteItem.setWidth(DensityUtil.dip2px(getActivity(), 64));
                    deleteItem.setTitle(R.string.delete);
                    deleteItem.setTitleSize(16);
                    deleteItem.setTitleColor(Color.WHITE);
                    menu.addMenuItem(deleteItem);
                }
            }
        };
        swipeMenuListView.setAdapter(addedCategoriesAdapter);
        swipeMenuListView.setOnItemClickListener(this);
        swipeMenuListView.setOnMenuItemClickListener(this);
        swipeMenuListView.setMenuCreator(creator);
        if (addedCategoriesAdapter.getCount() > 0) {
            inc_emptyView.setVisibility(View.VISIBLE);
        }
    }

    private void initLanguageRcv() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rcv_language.setLayoutManager(linearLayoutManager);
        DividerDecoration dividerDecoration = new DividerDecoration(getActivity(), linearLayoutManager.getOrientation(), true);
        rcv_language.addItemDecoration(dividerDecoration);
        rcv_language.setAdapter(languageListAdapter);
        languageListAdapter.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(int position) {
                if (position == 1) {
                    mainActivity.setLanguage("en");
                } else if (position == 2) {
                    mainActivity.setLanguage("zh");
                } else if (position == 3) {
                    mainActivity.setLanguage("fr");
                } else if (position == 4) {
                    mainActivity.setLanguage("de");
                } else if (position == 5) {
                    mainActivity.setLanguage("es");
                }

                if (position != languageListAdapter.getItemCount() - 1) {
                    mainActivity.setRightText(languageArray[position - 1]);
                }

                behavior2.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
    }

    private void initCategoryRcv() {
        rcv_category.setLayoutManager(new LinearLayoutManager(getActivity()));
        rcv_category.setItemAnimator(new DefaultItemAnimator());
        rcv_category.setPadding(DensityUtil.dip2px(getActivity(), 6), DensityUtil.dip2px(getActivity(), 6), DensityUtil.dip2px(getActivity(), 6), DensityUtil.dip2px(getActivity(), 6));
        SpacesItemDecoration spacesItemDecoration = new SpacesItemDecoration(DensityUtil.dip2px(getActivity(), 6));
        rcv_category.addItemDecoration(spacesItemDecoration);
        rcv_category.setAdapter(unAddedCategoriesAdapter);
        unAddedCategoriesAdapter.setOnUnAddedCategoryItemClickListener(new UnAddedCategoryAdapter.OnUnAddedCategoryItemClickListener() {
            @Override
            public void onItemClick(int position) {
                behavior1.setState(BottomSheetBehavior.STATE_COLLAPSED);
                Category category = unAddedCategories.get(position);
                category.setAdded(true);
                dataBaseDataSource.updateCategory(category.getId(), true);
                addedCategoriesAdapter.add(0, category);
                inc_emptyView.setVisibility(View.VISIBLE);
                unAddedCategories.remove(position);
                unAddedCategoriesAdapter.notifyItemRemoved(position);
                unAddedCategoriesAdapter.notifyItemRangeChanged(position, unAddedCategoriesAdapter.getItemCount());
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Category category = (Category) addedCategoriesAdapter.getItem(position);
        mController.setDeviceType(category.getType());
        mainActivity.showFragment(LightFragment.newInstance(category.getType()));
    }

    @Override
    public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
        if (index == 0) {
            Category category = (Category) addedCategoriesAdapter.getItem(position);
            category.setAdded(false);
            addedCategoriesAdapter.remove(category);
            dataBaseDataSource.updateCategory(category.getId(), false);
            if (addedCategoriesAdapter.getCount() == 0) {
                inc_emptyView.setVisibility(View.GONE);
            }
            unAddedCategories.add(category);
            unAddedCategoriesAdapter.notifyItemRangeChanged(position, unAddedCategoriesAdapter.getItemCount());
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.toolbar_right && (behavior2.getState() == BottomSheetBehavior.STATE_COLLAPSED || behavior2.getState() == BottomSheetBehavior.STATE_HIDDEN)) {
            if (behavior1.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                behavior1.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
            behavior2.setState(BottomSheetBehavior.STATE_EXPANDED);
        }
    }

    @Override
    public boolean onBackPressed() {
        if (behavior2.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            behavior2.setState(BottomSheetBehavior.STATE_COLLAPSED);
        } else if (behavior1.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            behavior1.setState(BottomSheetBehavior.STATE_COLLAPSED);
        } else {
            getActivity().moveTaskToBack(true);
        }
        return true;
    }


    private class BottomSheetCallback extends BottomSheetBehavior.BottomSheetCallback {

        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_COLLAPSED || newState == BottomSheetBehavior.STATE_HIDDEN) {
                blackView.setVisibility(View.GONE);
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            blackView.setVisibility(View.VISIBLE);
            ViewCompat.setAlpha(blackView, slideOffset);
        }
    }

}
